import { Component, OnInit, Input, ViewChild, ElementRef } from '@angular/core';
import { AuthGuardService } from '../../@core/auth-guard-service.guard';
import { Router, ActivatedRoute } from '@angular/router';
import { ToastService } from 'ng-devui';
import { DialogService } from 'ng-devui/modal'
import { TransferComponent } from './transfer/transfer.component';
@Component({
  selector: 'app-avatar-detail',
  templateUrl: './avatar-detail.component.html',
  styleUrls: ['./avatar-detail.component.scss'],
})
export class AvatarDetailComponent implements OnInit {
  //集合id
  collectionNum: any;
  //藏品tokenid
  colltoken: any;
  //藏品核验id
  collectionId: any;
  collectionDetail: any;
  @ViewChild('download', { read: ElementRef }) download: ElementRef;
  userId = parseInt(localStorage.getItem('userId'))

  constructor(
    private authGuardService: AuthGuardService,
    private dialogService: DialogService,
    private router: Router,
    private toastService: ToastService,
    private activatedRouter: ActivatedRoute,
  ) { }

  ngOnInit(): void {
    this.activatedRouter.queryParams.subscribe(queryParams => {
      this.collectionNum = queryParams['collectionIndex']
      this.colltoken = queryParams['tokenId']
    })
    this.authGuardService.getAssetsDetail(this.userId, this.collectionNum, this.colltoken).subscribe((res) => {
      if (res.code == 0) {
        this.collectionDetail = res.data
        this.collectionId = res.data.assetId
      }
      else {
        this.toastService.open({ value: [{ severity: 'error', summary: '', content: 'res.msg' }] })
      }
    })

  }

  toggleDownloadIcon(flag: string): void {
    let downloadEle = this.download.nativeElement;
    if (flag === 'in') {
      downloadEle.classList.add('active-download');
      downloadEle.classList.remove('normal-download');
    } else {
      downloadEle.classList.add('normal-download');
      downloadEle.classList.remove('active-download');
    }
  }

  downloadFile(content: any, fileName: any) {
    //下载base64图片
    var base64ToBlob = function (code) {
      let parts = code.split(';base64,');
      let contentType = parts[0].split(':')[1];
      let raw = window.atob(parts[1]);
      let rawLength = raw.length;
      let uInt8Array = new Uint8Array(rawLength);
      for (let i = 0; i < rawLength; ++i) {
        uInt8Array[i] = raw.charCodeAt(i);
      }
      return new Blob([uInt8Array], {
        type: contentType,
      });
    };
    let aLink = document.createElement('a');
    let blob = base64ToBlob(content);
    let evt = document.createEvent('HTMLEvents');
    evt.initEvent('click', true, true); //initEvent 不加后两个参数在FF下会报错  事件类型，是否冒泡，是否阻止浏览器的默认行为
    aLink.download = fileName;
    aLink.href = URL.createObjectURL(blob);
    aLink.click();
  }

  copyId(id: string) {
    if (navigator.clipboard && window.isSecureContext) {
      navigator.clipboard.writeText(id).then(() => {
        this.toastService.open({ value: [{ severity: 'success', summary: '', content: '复制成功' }] });
      }, () => {
      });
    } else {
      let textArea = document.createElement("textarea");
      textArea.value = id;
      textArea.style.position = "absolute";
      textArea.style.opacity = '0';
      textArea.style.left = "-999999px";
      textArea.style.top = "-999999px";
      document.body.appendChild(textArea);
      textArea.focus();
      textArea.select();
      new Promise((res, rej) => {
        // 执行复制命令并移除文本框
        document.execCommand('copy') ? this.toastService.open({ value: [{ severity: 'success', summary: '', content: '复制成功' }] }) : rej;
        textArea.remove();
      });
    }
  }

  submit() {
    this.openTransformDialog()
  }

  openTransformDialog() {
    const results = this.dialogService.open({
      id: 'dialog-service',
      width: '600px',
      maxHeight: '600px',
      title: '转赠',
      content: TransferComponent,
      backdropCloseable: true,
      dialogtype: 'standard',
      buttons: [
      ],
      data: {
        collectionNum: this.collectionId,
        close: ($event: Event) => {
          results.modalInstance.hide()
        }
      }
    })
  }

  verifyCollections() {
    this.authGuardService.getBlockChainType().subscribe((res) => {
      if (res.data.type === 'shared') {
        window.open('https://www.huaweicloud.com/product/bcs/dac.html');
      } else {
        this.router.navigate(['/blockchain']);
      }
    });
  }
}
